package com.zcsy.manage.service.quartz.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CommonConfig;
import com.zcsy.manage.model.property.FeeBill;
import com.zcsy.manage.model.property.FeeBillDetail;
import com.zcsy.manage.persistence.base.CellHouseDao;
import com.zcsy.manage.persistence.base.CommonConfigDao;
import com.zcsy.manage.persistence.property.FeeBillDao;
import com.zcsy.manage.persistence.property.FeeBillDetailDao;
import com.zcsy.manage.persistence.system.UserDao;
import com.zcsy.manage.service.quartz.IQuartzTaskService;

@Service
public class QuartzTaskServiceImpl implements IQuartzTaskService {

    @Autowired
    private CellHouseDao houseDao;
    
    @Autowired
    private UserDao userDao;

    @Autowired
    private FeeBillDao feeBillDao;

    @Autowired
    private FeeBillDetailDao billDetailDao;
    
    @Autowired
    private CommonConfigDao configDao;

    private Logger logger = Logger.getLogger(QuartzTaskServiceImpl.class);

    @Override
    public void clearIntegral() throws Exception {
        logger.info("clear integral start...");
        userDao.clearOwnerIntegral();
    }

    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();//可以对每个时间域单独修改

    }
    @Override
    public void createPropertyFee() throws Exception {
        logger.info("create preperty fee start...");

        List<FeeBillDetail> detailList = new ArrayList<>();

        List<FeeBill> latestList = feeBillDao.getLatestFeeBill();// 最后一次缴费或欠费账单
        
        List<CommonConfig> propertyConfig = configDao.getPropertyConfigByName(Constants.PROPERTY_PAY_TIME);
        Map<String, CommonConfig> configMap = new HashMap<>();
        for(CommonConfig config : propertyConfig) {
            configMap.put(config.getCellId(), config);
        }
        
        FeeBillDetail detailInfo = null;
        for (FeeBill bill : latestList) {
            Date latestDate = bill.getSendTime();// 获取最后一次缴费或欠费日期
            CellHouse cellHouse = houseDao.selectByPrimaryKey(bill.getHouseId());//根据房屋id查询房屋信息
            if(null == cellHouse) {
                logger.error("房层id不存在 【" + bill.getHouseId() + "】");
                continue;
            }
            String cellId = cellHouse.getCellId();
            
            boolean needCreate = false;
            try {
                int payDay = Integer.parseInt(configMap.get(cellId).getValue());
                int newDay = Calendar.getInstance().get(Calendar.DATE);
                
                needCreate = (payDay == newDay);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("配置信息错误: " + e.getMessage());
            }
            if(needCreate && null != latestDate && null != cellHouse && null != cellHouse.getPerPrice()) {
                /**
                 * 修改欠费账单生成逻辑： 
                 * 缴最后一次缴费或欠费日期 小于等于 当前日期，就生成欠费账单 
                 */
                
                if (DateUtils.getDays(latestDate) < 0) {

                    detailInfo = new FeeBillDetail();
                    detailInfo.setId(UniqueNumberUtils.get18UniqueNumber());
                    detailInfo.setBillId(bill.getId());
                    detailInfo.setStartDate(DateUtils.calDate(bill.getSendTime(), 1));// 一天以后的日期
                    
                   //将最后一次缴费日子往后推一个月
                    Calendar c = Calendar.getInstance();//获得一个日历的实例
                    c.setTime(latestDate);//设置日历时间
                    //c.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
                    c.add(Calendar.MONTH, Constants.STATE_ENABLED);//在日历的月份上增加1个月
                    Date lastDate = c.getTime();// 得到你想要的日期
                    detailInfo.setEndDate(lastDate);

                    detailInfo.setMonth(Constants.ONE_MONTH);// month 月数:一个月
                    detailInfo.setArea(cellHouse.getArea());// area 面积
                    detailInfo.setRate(BigDecimal.ONE);
                    detailInfo.setUnitPrice(cellHouse.getPerPrice());// unit_price 单价
                    // money 总价 = 单价*面积*倍率*月数
                    BigDecimal money = detailInfo.getUnitPrice().multiply(detailInfo.getArea())
                            .multiply(detailInfo.getRate()).multiply(new BigDecimal(Constants.ONE_MONTH));
                    detailInfo.setMoney(money);                                                                                      

                    detailInfo.setState(Constants.AFTER_STATE);//欠费
                    detailInfo.setGenerateWay(Constants.GENERATE_WAY_QUARTZ);
                    detailInfo.setCreateTime(new Date());

                    detailList.add(detailInfo);
                }
            }
        }
        if (detailList.size() > 0) {
            billDetailDao.batchInsertBillDetail(detailList);
        }
    }

    @Override
    public void createParkingFee() throws Exception {
        logger.info("create parking fee start...");
    }

}
